package com.bc.web.service;

import java.util.List;

import com.bc.common.CommonEnum.OrderStatus;
import com.bc.common.PayType;
import com.bc.web.config.R;
import com.bc.web.model.Account;
import com.fs.common.util.FSDate;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class ClearD0Task implements Runnable {

	@Override
	public void run() {
		String date = FSDate.getDate();
		System.out.println("清空d0Balance定时任务执行了");
		if (FSDate.isWorkday(date)) {
			List<Account> list = Account.dao.d0BalanceMoreThan0();
			for (Account a : list) {
				if ("hicardpay".equals(a.getChannelNo())) {
					String sql = "SELECT SUM(amount-merchFee) AS sumAcmount FROM trade_order WHERE payTime BETWEEN ? AND ? AND orderStatus=? AND payType IN(?,?,?,?) AND merchCode=? AND channelCode=?";
					Record record = Db.use(R.BD_TRADE).findFirst(sql, 
							date + " 00:00:00",
							date + " 08:59:59",
							OrderStatus.Success.getValue(),
							PayType.WECHAT_PUBLIC,
							PayType.WECHAT_QRCODE,
							PayType.ALIPAY_PUBLIC,
							PayType.ALIPAY_QRCODE,
							a.getAccountNo(),
							a.getChannelNo()
							);
					int sumAmount = record.getBigDecimal("sumAcmount") == null ?  0 : record.getBigDecimal("sumAcmount").intValue();
					Db.use(R.BD_TRADE).update("UPDATE account SET d0Balance=? WHERE accountNo=? AND channelNo=?", sumAmount, a.getAccountNo(), a.getChannelNo());
				}
				
				// 重置汇卡商户号对应的虚账账户D0余额
				if ("hicard".equals(a.getChannelNo())) {
					String sql = "SELECT SUM(amount-amount*0.0038) AS sumAcmount FROM trade_order WHERE payTime BETWEEN ? AND ? AND orderStatus=? AND payType IN(?,?,?,?) AND otherMerchCode=? AND channelCode=?";
					Record record = Db.use(R.BD_TRADE).findFirst(sql, 
							date + " 00:00:00",
							date + " 08:59:59",
							OrderStatus.Success.getValue(),
							PayType.WECHAT_PUBLIC,
							PayType.WECHAT_QRCODE,
							PayType.ALIPAY_PUBLIC,
							PayType.ALIPAY_QRCODE,
							a.getAccountNo(),
							"hicardpay"
							);
					int sumAmount = record.getBigDecimal("sumAcmount") == null ?  0 : record.getBigDecimal("sumAcmount").intValue();
					Db.use(R.BD_TRADE).update("UPDATE account SET d0Balance=? WHERE accountNo=? AND channelNo=?", sumAmount, a.getAccountNo(), a.getChannelNo());
				}
			}
		}
	}

}
